layui.define(function (exports) {
  var $ = layui.$,
    admin = layui.admin,
    setter = layui.setter,
    laytpl = layui.laytpl,
    form = layui.form;
  var params = {};

  function initProductList() {
    if (sessionStorage.category === 'CHANNEL' || sessionStorage.category === 'CHANNEL_SUB_ACC') {
      params = {
        isMall: 0
      };
    } else {
      params = {
        isJhzb: 0
      };
    }

    // 初始化表单
    form.render(null, 'LAY_wisdom_product_center_search_form');

    // 表单提交
    form.on('submit(LAY_wisdom_product_center_search_btn)', function (data) {
      var field = data.field;
      params = $.extend(true, params, field);
      generateProductList(params);

      return false;
    });

    generateProductList(params);
  }

  function initEvents() {
    $('.LAY_product_center_add').off('click').on('click', function () {
      var productCode = $(this).data('code');
      var center = layui.center;
      center.add(productCode);
      generateProductList(params);
    });
  };

  // 产品列表
  function generateProductList(params) {
    admin.req({
      url: setter.url + '/product/getProductListMall',
      type: 'GET',
      data: params,
      done: function (res) {
        var data = res.data || [];

        renderData(data, function () {
          form.render(null, 'LAY_wisdom_product_center_list_form');
          initEvents();
        });
      }
    })
  }

  // 渲染数据
  function renderData(data, callback) {
    var getTpl = $('#LAY_wisdom_product_center_list_tpl').html();

    if (!getTpl) {
      return;
    }

    laytpl(getTpl).render(data, function (html) {
      $('#LAY_wisdom_product_center_list_view').html(html);

      if (typeof (callback) === 'function') {
        callback();
      }
    });
  }

  exports('centerProductLibrary', {
    init: initProductList,
    refresh: function () {
      generateProductList(params);
    }
  });
});